# -*- coding: utf-8 -*-
from django import template
from django.conf import settings
from django.template.defaultfilters import safe
from django.template import Template, Context

#from formatfilters.text.utils import clean_str, bulkreplace
import djwheel.app.templatetools.text.typo as typograph
import djwheel.app.templatetools.text.wiki as wiki
from djwheel.app.templatetools import human
import re

register = template.Library()

@register.filter
def typo(s):
    return safe(typograph.process_html(s))

@register.filter
def wikiinline(s):
    return safe(wiki.wikiinline(s))

@register.filter
def wikiblock(s):
    return safe(wiki.wikiblock(s))

@register.filter
def render(s, vars=None):
    try:
        return safe(Template(s).render(Context(vars or {})))
    except Exception, e:
        return safe('<!-- ERROR: %s --> %s' % (e, s))

@register.filter
def numeral(s, low_mid_hi):
    try:
        low, mid, hi = low_mid_hi.split('|')
    except:
        raise Exception('`numeral` filter second parameter must have "s|s|s" format')
    try:
        num = int(s)
    except ValueError:
        return s
    if '%d' in low and '%d' in mid and '%d' in hi:
        return safe(human.numeral_suffix(num, low, mid, hi) % num)
    else:
        return safe("%d&nbsp;%s" % (num, human.numeral_suffix(num, low, mid, hi)))

#try:
#    perfecttext_filters = settings.FORMATFILTERS_PERFECTTEXT
#    perfecttext_filters = perfecttext_filters.split('|')
#except AttributeError:
#    perfecttext_filters = ['typo', 'pformat']
#
#def multiply_func(funcs):
#    bits = list(funcs)
#    bits.reverse()
#    return eval('lambda s: ' + '('.join(bits + ['s']) + ')'*len(bits))
#
#perfecttext = multiply_func(perfecttext_filters)
##print perfecttext
#def perfecttext(s):
#    return pformat(s)
#register.filter(perfecttext)
